package cn.xtits.xtp.controller;

import cn.xtits.xtf.common.utils.HttpClientUtil;
import cn.xtits.xtf.common.utils.JsonUtil;
import cn.xtits.xtf.common.utils.JwtUtil;
import cn.xtits.xtf.common.web.AjaxResult;
import cn.xtits.xtp.dto.UserOpenDto;
import cn.xtits.xtp.entity.*;
import cn.xtits.xtp.enums.ErrorCodeEnums;
import cn.xtits.xtp.interceptor.LoginToken;
import cn.xtits.xtp.service.AppService;
import cn.xtits.xtp.service.UserOpenService;
import cn.xtits.xtp.service.UserService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/userOpen")
public class UserOpenController extends BaseController {

    @Value("${REST_XTP_URL}")
    private String REST_XTP_URL;

    @Value("${APP_TOKEN}")
    private String APP_TOKEN;

    @Value("${wx.appid}")
    private String APPID;

    @Value("${wx.secret}")
    private String SECRET;

    Gson gson = new GsonBuilder().serializeNulls().create();

    @Autowired
    private UserOpenService userOpenService;

    @Autowired
    private AppService appService;

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "updateUser")
    public AjaxResult updateUser(
            @RequestParam(value = "data", required = false) String data) {
        UserOpenDto record = JsonUtil.fromJson(data, UserOpenDto.class);
        Integer userId = record.getUserId();
        User user = new User();
        user.setId(userId);
        user.setPhone(record.getPhone());
        user.setName(record.getName());
        user.setModifyDate(new Date());
        return new AjaxResult(ErrorCodeEnums.NO_ERROR.value);

    }

    @RequestMapping(value = "updateOpenUser")
    @ResponseBody
    public AjaxResult updateUserInfo(
            @RequestParam(value = "data", required = false) String data) {
        UserOpenDto record = JsonUtil.fromJson(data, UserOpenDto.class);
        App app = appService.getByPrimaryKey(record.getAppId());
        if (app == null) {
            return new AjaxResult(-1, "AppId不存在!");
        }
        if (StringUtils.isBlank(record.getName())) {
            return new AjaxResult(-1, "姓名不能为空!");
        }
        if (StringUtils.isBlank(record.getPhone())) {
            return new AjaxResult(-1, "电话不能为空!");
        }
        UserExample example = new UserExample();
        example.setPageSize(1);
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andAccountEqualTo(record.getAccount());
        criteria.andPasswordEqualTo(record.getPassword());
        criteria.andDeleteFlagEqualTo(false);
        //criteria.andAppIdEqualTo(app.getId());
        List<User> list = userService.listByExample(example);

        if (list.size() > 0) {
            User user = list.get(0);
            user.setName(record.getName());
            user.setPhone(record.getPhone());
            userService.updateByPrimaryKeySelective(user);
            UserOpen userOpen = new UserOpen();
            userOpen.setUserId(user.getId());
            userOpen.setAppId(record.getAppId());
            userOpen.setAvatar(record.getAvatar());
            userOpen.setOpenId(record.getOpenId());
            userOpen.setOpenType(record.getOpenType());
            userOpen.setNickName(record.getNickName());
            userOpen.setAccessToken(record.getAccessToken());
            userOpen.setDeleteFlag(false);

            UserOpen openByOpenId = userOpenService.getUserOpenByOpenId(record.getOpenId());
            if (openByOpenId == null) {
                userOpenService.insertUserOpen(userOpen);
            }
            else {
                if (openByOpenId.getUserId() != userOpen.getUserId()) {
                    openByOpenId.setUserId(userOpen.getUserId());
                    userOpenService.updateByPrimaryKeySelective(openByOpenId);
                }
            }
            try {
                LoginToken t = new LoginToken();
                t.setAppId(user.getAppId());
                t.setUserId(user.getId());
                t.setUserName(user.getName());
                t.setAppToken(app.getToken());
                String authToken = JsonUtil.toJson(t);
                String token = JwtUtil.createJWT(user.getId().toString(), authToken, 24 * 60 * 60 * 1000);
                try {
                    String key = "jwt:" + String.valueOf(user.getId());
                    ValueOperations<String, String> ops = template.opsForValue();
                    ops.set(key, token, 60 * 24, TimeUnit.MINUTES);
                } catch (Exception e) {

                }
                Map<String, Object> map = new HashMap<>();
                map.put("first", true);
                map.put("token", token);
                return new AjaxResult(1, "", map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return new AjaxResult(-1, "绑定账户密码不正确！");

        }
        return null;
    }

    @RequestMapping(value = "loginUserOpen")
    @ResponseBody
    public AjaxResult loginUserOpen(
            @RequestParam(value = "appId", required = false) Integer appId,
            @RequestParam(value = "openType", required = false) String openType,
            @RequestParam(value = "openId", required = false) String openId,
            @RequestParam(value = "accessToken") String accessToken,
            @RequestParam(value = "avatar", required = false) String avatar,
            @RequestParam(value = "nickName", required = false) String nickName) {

        UserOpenExample example = new UserOpenExample();
        example.setPageSize(1);
        UserOpenExample.Criteria criteria = example.createCriteria();
        criteria.andDeleteFlagEqualTo(false);
        criteria.andOpenIdEqualTo(openId);
        criteria.andOpenTypeEqualTo(openType);
        if (appId != null) {
            criteria.andAppIdEqualTo(appId);
        }
        //criteria.andAppIdEqualTo(app.getId());
        List<UserOpen> list = userOpenService.listByExample(example);
        App app = appService.getByPrimaryKey(appId);
        if (list.size() > 0) {
            UserOpen userOpen = list.get(0);
            User user = userService.getByPrimaryKey(userOpen.getUserId());
            if (user == null || user.getDeleteFlag()) {
                return new AjaxResult(-1, "账号异常,请联系管理员!");
            }
            boolean firstFlag = false;
            String userName = user.getName();
            if (StringUtils.isBlank(user.getName())) {
                firstFlag = true;
                userName = userOpen.getNickName();
            }
            try {
                LoginToken t = new LoginToken();
                t.setAppId(userOpen.getAppId());
                t.setUserId(userOpen.getUserId());
                t.setUserName(userName);
                t.setAppToken(app.getToken());
                String authToken = JsonUtil.toJson(t);
                String token = JwtUtil.createJWT(userOpen.getUserId().toString(), authToken, 24 * 60 * 60 * 1000);
                try {
                    String key = "jwt:" + String.valueOf(userOpen.getUserId());
                    ValueOperations<String, String> ops = template.opsForValue();
                    ops.set(key, token, 60 * 24, TimeUnit.MINUTES);
                } catch (Exception e) {

                }
                Map<String, Object> map = new HashMap<>();
                map.put("first", firstFlag);
                map.put("token", token);
                return new AjaxResult(ErrorCodeEnums.NO_ERROR.value, "", map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

            return new AjaxResult(-1, "用户不存在");
        }
        return new AjaxResult(ErrorCodeEnums.NORMAL_ERROR.value, "登录失败");

    }

    @RequestMapping(value = "getUserOpenByUser")
    @ResponseBody
    public AjaxResult getUserOpenByUser(
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "openType", required = false) String openType) {
        if (StringUtils.isBlank(openType)) {
            return new AjaxResult(-1, "请传入类型!");
        }
        if (userId == null || userId < 1) {
            userId = getUserId();
        }
        if (userId == null || userId < 1) {
            return new AjaxResult(-1, "获取用户信息异常!");
        }
        UserOpenExample userOpenExample = new UserOpenExample();
        userOpenExample.setPageSize(1);
        UserOpenExample.Criteria userOpenExampleCriteria = userOpenExample.createCriteria();
        userOpenExampleCriteria.andDeleteFlagEqualTo(false)
                .andOpenTypeEqualTo(openType)
                .andUserIdEqualTo(userId);
        List<UserOpen> userOpenList = userOpenService.listByExample(userOpenExample);
        if (userOpenList.size() > 0) {
            return new AjaxResult(userOpenList.get(0));
        }
        return new AjaxResult();
    }

    @RequestMapping(value = "jscode2session")
    @ResponseBody
    public AjaxResult jscode2session(
            @RequestParam(value = "code", required = false) String code) {
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
            System.out.println(url);
            String res = HttpClientUtil.doGet(url);
            Jscode jscode = JsonUtil.fromJson(res, Jscode.class);
            return new AjaxResult(jscode);
        } catch (Exception ex) {
            return new AjaxResult(ex.getMessage());
        }
    }
}
